package com.thinkgem.jeesite.modules.spider.pipeline;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.thinkgem.jeesite.modules.cms.entity.Article;
import com.thinkgem.jeesite.modules.cms.entity.ArticleData;
import com.thinkgem.jeesite.modules.spider.common.SpiderConstants;
import com.thinkgem.jeesite.modules.spider.entity.SpiderLog;
import com.thinkgem.jeesite.modules.spider.service.SpiderLogService;
import com.thinkgem.jeesite.modules.wordpress.dao.WpPostsMapper;
import com.thinkgem.jeesite.modules.wordpress.entity.WpPostsWithBLOBs;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

@Component
public class CnblogsPipeline4Wordpress implements Pipeline {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private WpPostsMapper wppostMapper;
	@Autowired
	private SpiderLogService logService;
	

	@Override
	public void process(ResultItems resultItems, Task task) {
		Article article = resultItems.get("article");
		ArticleData articleData = resultItems.get("articleData");
		Date now = new Date();
		
		WpPostsWithBLOBs post = new WpPostsWithBLOBs();
		post.setPostAuthor(1L);
		post.setPostDate(now);
		post.setPostDateGmt(now);
		post.setPostContent(articleData.getContent());
		post.setPostTitle(article.getTitle());
		post.setPostExcerpt("");
		post.setPostStatus("pending");
		post.setCommentStatus("open");
		post.setPingStatus("open");
		post.setPostPassword("");
		post.setPostName(article.getTitle());
		post.setToPing("");
		post.setPinged("");
		post.setPostModified(now);
		post.setPostModifiedGmt(now);
		post.setPostContentFiltered("");
		post.setPostParent(0L);
		post.setGuid("");
		post.setMenuOrder(0);
		post.setPostType("post");
		post.setPostMimeType("");
		post.setCommentCount(0L);
		
		
		if (article != null && articleData != null) {
			try {
				wppostMapper.insert(post);
			} catch (Exception e) {
				logService.save(new SpiderLog("ArticleData", SpiderConstants.LOG_LEVEL_ERROR, e.getLocalizedMessage()));
				logger.error("insert article error !");
				e.printStackTrace();
			}
			logger.debug("articleTitle==>" + article.getTitle());
		}

	}

}
